﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace NewsPortal.Web.Infrastructure.Helpers
{
    public static class ExHtmlHelperExtensions
    {
        public static MvcHtmlString CreateSelectList<T>(this HtmlHelper source, 
            IEnumerable<T> items,
            string dataTextField,
            string dataValueField, 
            T selectedItem, 
            Dictionary<string, string> htmlAttributes) where T: class
        {
            TagBuilder builder = new TagBuilder("select");
            StringBuilder sb = new StringBuilder();
            Type type = typeof(T);

            foreach (var item in items)
            {
                TagBuilder optionBuilder = new TagBuilder("option");
                var propValue = type.GetProperty(dataValueField).GetValue(item);
                var propText = type.GetProperty(dataTextField).GetValue(item) ?? "No title";
                optionBuilder.Attributes.Add(new KeyValuePair<string, string>("value", propValue.ToString()));
                optionBuilder.InnerHtml = propText.ToString();
                builder.InnerHtml += optionBuilder;
            }

            if (htmlAttributes != null)
            {
                foreach (var item in htmlAttributes)
                {
                    builder.Attributes.Add(item);
                }
            }
            return MvcHtmlString.Create(builder.ToString());
        }
    }
}